<template>
    <div class="Accvip">
          <div class="title_bt">
            <div class="bt on" @click="adduser()"><i class="el-icon-s-custom"></i>新增管理员</div>
            <span>说明:可设置不同角色以及对应权限</span>
            <div class="search">
                <el-input v-model="datapage.name" @change="search()" placeholder="请输入搜索的账号"></el-input>
                <div class="button"  @click="search()"><i class="el-icon-search"></i></div>
            </div>
        </div>
        <el-table :data="tableData" style="width: 100%" class="tablebox" border>
            <el-table-column prop="id" label="编号" width="80" align="center"></el-table-column>
            <el-table-column prop="username" label="用户名"  width="180"></el-table-column>
            <el-table-column prop="status" label="状态" width="80" align="center">
                 <template slot-scope="{ row }">
                        <el-tag size='mini'
                         :type="row.status==0? 'danger' : row.status==1? 'success' :'info'">
                          {{row.status==0?'删除':  row.status==1 ?  '有效' :'失效'}}
                        </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="permission" label="用户权限">
                  <template slot-scope="{ row }">
                    <p>{{roleslist(row.permission)}}</p>
                </template>
            </el-table-column>
            <el-table-column prop="created_at" label="添加时间" align="center" width="180">
                <template slot-scope="{ row }">
                    <p>{{$formateDate(row.created_at)}}</p>
                </template>
            </el-table-column>
            <el-table-column prop="updated_at" label="修改时间" align="center"  width="180">
                 <template slot-scope="{ row }">
                    <p>{{$formateDate(row.updated_at)}}</p>
                </template>
            </el-table-column>
            <el-table-column class-name="status-col"  label="操作" width="180"  align="center"  fixed="right">
                <template slot-scope="{ row }">
                    <kt-button  size='mini' label="修改密码" type="text" @click="handleUpdate(row)"/>
                    <kt-button  size='mini' label="修改权限" type="text" @click="premission(row)"/>
                    <kt-button  size='mini' label="删除" type="text" @click="handleDelete(row)"/>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            class="pageswarp"
            :background="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=datapage.page
            :page-size=page_size
            layout="total, prev, pager, next, jumper"
            :total=total>
        </el-pagination>
         <!-- 弹出修改用户信息的表单 -->
        <el-drawer
            :title="usertitle"
            :visible.sync="drawer"
            :before-close="handleClose"
            custom-class="demo-drawer"
            ref="drawer"
             size="90%">
                <div class="demo-drawer__content">
                    <div class="demo-drawer__content_from">
                        <div class="from">
                            <el-form :model="userForm" :rules="rules" ref="userFormadd"  label-width="100px" >
                                <el-form-item label="用户名：" prop="user">
                                    <el-input v-model="userForm.user"></el-input>
                                     <p>用户名允许使用大小写英文字母，中文，数字</p>
                                </el-form-item>
                                 <el-form-item label="密码："   prop="pwd">
                                    <el-input  type="text"  v-model="userForm.pwd"  ></el-input>
                                  <p>至少6位，最长32位，必须包含大小写字母，数字，除空格以外的特殊符号</p>
                                </el-form-item>
                                <el-form-item label="确认密码："   prop="checkpasswd">
                                    <el-input type="password" v-model="userForm.checkpasswd"  ></el-input>
                                     <p>请重复上面输入的密码以确认输入正确</p>
                                </el-form-item>
                                 <el-form-item label="权限设置：" >
                                     <el-button type="primary" @click="premission()">页面权限</el-button>
                                </el-form-item>
                                <p>{{roleslist(roles)}}</p>
                            </el-form>
                        </div>
                        <div class="demo-drawer__footer">
                            <el-button @click="handleClose">取 消</el-button>
                            <el-button type="primary"  @click="submitForm('userFormadd')" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
                        </div>
                    </div>
               
                </div>
        </el-drawer>
        <!-- 修改密码 -->
        <el-dialog :title="'重置'+username+'密码'" :close-on-click-modal="false" :visible.sync="dialogFormVisible" width="520px" center>
            <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px" >
                <el-form-item label="密码："  prop="pwd">
                    <el-input  type="password"  v-model="userForm.pwd"  ></el-input>
                    <p>6-20位字母和数字组合</p>
                </el-form-item>
                <el-form-item label="确认密码："  prop="checkpasswd">
                    <el-input  type="password"  v-model="userForm.checkpasswd"  ></el-input>
                    <p>请重复上面输入的密码以确认输入正确</p>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('userForm')" >确 定</el-button>
            </div>
        </el-dialog>
         <!-- 弹出修改用户权限的树菜单 -->
        <el-drawer
            title="用户权限"
            :append-to-body="true"
            custom-class="demo-drawer"
            :visible.sync="innerDrawer" size="50%">
                <div class="demo-drawer__content">
                <div class="demo-drawer__content_from"  v-if='innerDrawer'>
                    <div class="from">
                        <el-tree
                            ref="tree"
                            :data="treearr"
                            show-checkbox
                            default-expand-all
                            node-key="id"
                            :default-checked-keys="roles"
                            :props="defaultProps">
                        </el-tree>
                    </div>
                    <div class="demo-drawer__footer">
                        <el-button type="primary" @click="opentree">确定</el-button>
                        <span class="but" @click="innerDrawer=false">取 消</span>
                        <div class="fr">
                                <el-checkbox v-model="checkedtreearr" @change='checked_treearr'>全选</el-checkbox>
                        </div>
                    </div>
                </div>
            </div>
        </el-drawer>
    </div>
</template>
<script>
import KtButton from "@/components/elbutton"
 import { axios_user } from "@/api/infor";
 import { login} from "@/api/user";

    export default {
        name:'Admin',
        data(){
            // 输入密码
            var validatePass = (rule, value, callback) => {
                // var regusername =  /(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{6,32}/;
                var regusername =  /(?=.*[0-9])(?=.*[a-zA-Z]).{6,20}/;
                if (value === '') {
                callback(new Error('请输入密码'));
                } else if (!regusername.test(value) ) {
                    callback(new Error('至少6位，最长20位，必须包含字母，数字，除空格的特殊符号'));
                }else {
                    callback();
                }
            };
            // 输入密码重复的密码
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                 callback(new Error('请再次输入密码'));
                } else if (value !== this.userForm.pwd) {
                 callback(new Error('两次输入密码不一致!'));
                } else {
                    callback()
                }
            };
            // 验证邮箱
            var validateemail= (rule, value, callback) => {
                var regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
                if (value === '') {
                callback(new Error('请输入邮箱'));
                } else if (!regEmail.test(this.userForm.email) ) {
                callback(new Error('输入的邮箱格式不正确'));
                } else {
                callback();
                }
            };
            return{
                pages:1,
                searchinput:'',  //顶部的搜索栏目
                tableData: [   //表格的数据
                    
                ],
                usertitle:'新建账号',
                username:'',
                loading: false,
                drawer: false,
                dialogFormVisible:false,
                innerDrawer: false,
                page_size:1,
                total:1,
                datapage:{
                    name:'',
                    page:1,
                },
                roles:'',
                routerid:[],
                premissiontype:'新增权限',
                userForm:{
                    id:'',
                    user:'',
                    pwd:'',
                    permission:'',
                    checkpasswd:'',
                    type:'',
                },
                rules:{
                    name: [
                        { required: true, message: '最多输入100个字符', trigger: 'blur' }
                    ],
                    user: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 20, message: '用户名允许使用大小写英文字母，中文，数字', trigger: 'blur' }
                    ],
                    pwd: [
                         {required: true, validator: validatePass, trigger: 'blur' },
                        // {required: true, min: 6, max:32, message: '至少6位，最长32位，必须包含小写字母 ，大写字母和阿拉伯数字三种字符', trigger: 'blur' }
                    ],
                    checkpasswd: [
                        { required: true,validator: validatePass2, trigger: 'blur' },
                    ],
                    email: [
                          {required: true, validator: validateemail, trigger: 'blur' },
                    ]
                    
                },
                treearr:[],
                checkedtreearr:false,
                defaultProps: {
                    children: 'children',
                    label: 'label'
                }
            }
        },
        components:{
            KtButton,
        },
        created(){
             this.getdatalist("refresh")
        },
        mounted(){
             this.getTreeDate(this.$store.getters.roterslist,this.treearr);  //获取路由菜单
        },
        computed:{
        },
        methods:{
              roleslist(data){
                if(data){
                    let arra=[];
                    let data2;
                    if(Array.isArray(data)){
                         data2=data;
                    }else{
                         data2=data.split(',');
                    }
                   var arrfun= function (obj){
                        obj.forEach((item)=>{
                            if(typeof item.hidden==='undefined'){
                                if(item.meta){
                                    if(item.children){
                                        arrfun(item.children)
                                    }else{
                                        if( data2.includes(item.meta.id)){
                                            arra.push(item.meta.title)
                                        }
                                    }
                                }else{
                                    if( data2.includes(item.children[0].meta.id)){
                                        arra.push(item.children[0].meta.title)
                                    }
                                }
                            }
                        })
                    }
                    arrfun(this.$store.getters.roterslist)
                   return   arra.length==0 ? arra='' : arra;
                }
            },
            search(){
                 this.getdatalist("refresh")
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                 this.datapage.page=val;
                this.getdatalist();
            },
            // 新增用户
            adduser(){
                this.drawer=true;
                this.userForm.pwd='',
                this.userForm.checkpasswd='',
                 this.$nextTick(()=>{
                    this.$refs["userFormadd"].resetFields();
                })
            },
            // 修改用户
            handleUpdate(item){
                this.username=item.username;
                this.dialogFormVisible=true;
                this.userForm.id=item.id;
                this.userForm.pwd='',
                this.userForm.checkpasswd='',
                  this.$nextTick(()=>{
                    this.$refs["userForm"].resetFields();
                })
            },
            // 显示权限
            premission(item){
                 this.innerDrawer=true;
                 this.checkedtreearr=false;
                if(item){
                    this.roles=item.permission.split(',');
                    this.userForm.id=item.id;
                    this.userForm.user=item.username;
                    this.premissiontype='修改权限';
                }else{
                    this.roles=[];
                    this.premissiontype='新增权限';
                }
            },
             // 删除用户
            handleDelete(item){
                this.$confirm('确定要删除用户数据吗？','确认删除',{customClass:'layeralterelbox'}) .then(()  => {
                    this.userForm.id=item.id;
                    this.userForm.user=item.username;
                    this.axioslogin('remove');

                }).catch(()  => {});

            },
            // 确认关闭新建二级账号
            handleClose() {
                this.$confirm('确定要关闭吗','确认信息',{customClass:'layeralterelbox'}) .then(()  => {
                     this.drawer=false;
                }).catch(()  => {});
            },
            // 提交个人信息
            submitForm(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.axioslogin(formName)
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            // 请求修改信息得接口
            axioslogin(type){
                this.loading = true;
                let data_='';
                    // 修改密码
                    console.log(type)
                if(type=='userForm'){
                    data_={
                        id:this.userForm.id,
                        user:this.username,
                        pwd:this.userForm.pwd,
                        type:'1',
                        sign:this.$md5(this.$store.state.app.md5)
                    }
                }
                //注册用户
                else if(type=='userFormadd'){  
                    data_={
                        user:this.userForm.user,
                        pwd:this.userForm.pwd,
                        permission:this.roles.join(),
                        type:'3',
                        sign:this.$md5(this.$store.state.app.md5)
                    }
                }
                // 删除
                else if(type=='remove'){  
                    data_={
                        id:this.userForm.id,
                        user:this.userForm.user,
                        type:'4',
                        sign:this.$md5(this.$store.state.app.md5)
                    }
                }
                else{  //修改权限
                    data_={
                        id:this.userForm.id,
                         user:this.userForm.user,
                        permission:this.roles.join(),
                        type:'2',
                        sign:this.$md5(this.$store.state.app.md5)
                    }
                }
                console.log(data_)
                login(data_).then((res) => {
                    if(res.data.code==1){
                        this.loading=false;
                        this.dialogFormVisible=false;
                        this.drawer=false;
                        this.innerDrawer=false;
                        this.getdatalist("refresh")  
                    }else{
                        this.loading=false;
                         this.$message.error(res.data.msg);
                    }
                }).catch(( )=>{})

            },
            // 关闭权限树菜单
            opentree(){
                let arr=this.$refs.tree.getCheckedKeys().filter(item => item!==undefined )
                 this.roles=arr;
                if(this.premissiontype=='修改权限'){
                     this.axioslogin();
                }else{
                   this.innerDrawer=false;
                }
            },
            //树菜单全选
            checked_treearr(val){
                this.$refs.tree.setCheckedKeys(val ? this.routerid : []);
            },
            // 获取树菜单
            getTreeDate(obj,arrt){
                let that=this;
                obj.forEach((item)=>{
                    if(typeof item.hidden==='undefined'){
                          if(item.meta){
                           
                            if(item.meta.Level && item.children.length==1){
                                 arrt.push({label:item.children[0].meta.title,id:item.children[0].meta.id,children:[]})
                                if(item.children[0].meta.id){
                                    that.routerid.push(item.children[0].meta.id)
                                }
                            }else{
                                //  console.log(item.children.length)
                                 let obj={label:item.meta.title,id:item.meta.id, children:[]};
                                arrt.push(obj)
                                if(item.meta.id){
                                    that.routerid.push(item.meta.id)
                                }
                                if(item.children){
                                    this.getTreeDate(item.children,obj.children)
                                }
                            }
                          } 
                    }
                })
            },
            // 获取选中的树菜单
              userrouter(obj,arr){
                   obj.forEach((item)=>{
                       if(item.label){
                        arr.push(item.label)
                        if(item.children){
                            this.userrouter(item.children,arr)
                        }
                        }else{
                             arr.push(item.item.children[0].label)
                        }
                    })
                },
                getdatalist(type){
                    if(type=="refresh"){
                        this.datapage.page=1;
                    }
                    axios_user(this.datapage).then((res) => {
                        if(res.data.code==1){
                            this.loading=false;
                            this.tableData=res.data.data;
                            this.page_size=res.data.page_size;
                            this.total=Number(res.data.total);
                        }else{
                            this.loading=false;
                            this.tableData=[];
                            this.page_size=1;
                            this.total=0;
                            this.$message.error(res.data.msg);
                        }
                    }).catch(( )=>{})
                }
           
        }
    }
</script>
<style lang="scss" scoped>
   .usernamebbox{
      background-color: #e3eaf9;
      padding: 20px;
      margin-bottom: 20px;
      border-radius: 5px;
      line-height: 30px;
      font-size: 14px;
      p{
        margin: 10px 0;
        color: #606266;
        i{
            font-size: 20px;
            margin-right: 5px;
        }
        & > span{
            min-width: 115px;
            display: inline-block;
            
        }
      }
      u{
        text-decoration: none;
        color:#e46f31
      }
      
       
   } 
</style>
<style>
    .el-button--text{
        padding: 3px !important;
    }
    .el-button--text + .el-button--text{
       margin-left: 5px !important;
    }
      </style>